<template>
  <view class="record-page">
    <!-- 筛选条件 -->
    <view class="filter-section">
      <u-card :border="false">
        <view class="filter-content">
          <view class="filter-item">
            <text class="filter-label">时间范围</text>
            <u-picker
              :show="showTimeRangePicker"
              :columns="timeRangeOptions"
              @confirm="onTimeRangeChange"
              @cancel="showTimeRangePicker = false"
            >
              <u-button 
                :text="getTimeRangeText(filterData.timeRange)"
                type="info"
                size="small"
                plain
                @click="showTimeRangePicker = true"
              ></u-button>
            </u-picker>
          </view>
          <view class="filter-item">
            <text class="filter-label">车辆</text>
            <u-picker
              :show="showVehiclePicker"
              :columns="vehicleOptions"
              @confirm="onVehicleChange"
              @cancel="showVehiclePicker = false"
            >
              <u-button 
                :text="getVehicleText(filterData.vehicleId)"
                type="info"
                size="small"
                plain
                @click="showVehiclePicker = true"
              ></u-button>
            </u-picker>
          </view>
          <view class="filter-item">
            <text class="filter-label">状态</text>
            <u-picker
              :show="showStatusPicker"
              :columns="statusOptions"
              @confirm="onStatusChange"
              @cancel="showStatusPicker = false"
            >
              <u-button 
                :text="getStatusText(filterData.status)"
                type="info"
                size="small"
                plain
                @click="showStatusPicker = true"
              ></u-button>
            </u-picker>
          </view>
        </view>
      </u-card>
    </view>
    
    <!-- 统计信息 -->
    <view class="stats-section">
      <u-card :border="false">
        <view class="stats-content">
          <view class="stats-item">
            <text class="stats-number">{{ stats.totalCount }}</text>
            <text class="stats-label">总记录</text>
          </view>
          <view class="stats-item">
            <text class="stats-number">{{ stats.totalFee }}</text>
            <text class="stats-label">总费用</text>
          </view>
          <view class="stats-item">
            <text class="stats-number">{{ stats.avgDuration }}</text>
            <text class="stats-label">平均时长</text>
          </view>
        </view>
      </u-card>
    </view>
    
    <!-- 记录列表 -->
    <view class="record-list">
      <u-card title="停车记录" :border="false">
        <view class="list-content">
          <view 
            v-for="record in filteredRecords" 
            :key="record.id"
            class="record-item"
            @click="viewDetail(record)"
          >
            <view class="record-header">
              <view class="record-info">
                <text class="record-plate">{{ record.plateNumber }}</text>
                <u-tag :text="record.statusText" :type="record.statusType" size="mini"></u-tag>
              </view>
              <text class="record-fee" v-if="record.fee > 0">¥{{ record.fee }}</text>
            </view>
            
            <view class="record-details">
              <view class="detail-row">
                <text class="detail-label">入场时间：</text>
                <text class="detail-value">{{ record.entryTime }}</text>
              </view>
              <view class="detail-row" v-if="record.exitTime">
                <text class="detail-label">出场时间：</text>
                <text class="detail-value">{{ record.exitTime }}</text>
              </view>
              <view class="detail-row" v-if="record.duration">
                <text class="detail-label">停车时长：</text>
                <text class="detail-value">{{ record.duration }}</text>
              </view>
              <view class="detail-row" v-if="record.location">
                <text class="detail-label">停车位置：</text>
                <text class="detail-value">{{ record.location }}</text>
              </view>
            </view>
            
            <view class="record-actions">
              <u-button 
                type="primary" 
                text="查看详情"
                size="mini"
                @click.stop="viewDetail(record)"
              ></u-button>
              <u-button 
                v-if="record.status === 'completed' && record.fee > 0"
                type="warning" 
                text="重新缴费"
                size="mini"
                @click.stop="rePay(record)"
              ></u-button>
            </view>
          </view>
        </view>
        
        <!-- 加载更多 -->
        <view class="load-more" v-if="hasMore">
          <u-button 
            type="info" 
            text="加载更多"
            size="small"
            :loading="loading"
            @click="loadMore"
          ></u-button>
        </view>
        
        <!-- 无数据提示 -->
        <view class="empty-state" v-if="filteredRecords.length === 0">
          <u-icon name="file-text" color="#ccc" size="48"></u-icon>
          <text class="empty-text">暂无停车记录</text>
        </view>
      </u-card>
    </view>
  </view>
</template>

<script setup>
/**
 * 停车记录页面
 * @author Wu.Liang
 * @date 2025-01-21
 */

import { ref, reactive, computed, onMounted } from 'vue'

// 筛选数据
const filterData = reactive({
  timeRange: '7days',
  vehicleId: 'all',
  status: 'all'
})

// 时间范围选项
const timeRangeOptions = ref([
  { text: '最近7天', value: '7days' },
  { text: '最近30天', value: '30days' },
  { text: '最近3个月', value: '3months' },
  { text: '全部时间', value: 'all' }
])

// 车辆选项
const vehicleOptions = ref([
  { text: '全部车辆', value: 'all' },
  { text: '京A12345', value: '1' },
  { text: '京B67890', value: '2' }
])

// 状态选项
const statusOptions = ref([
  { text: '全部状态', value: 'all' },
  { text: '停车中', value: 'parking' },
  { text: '已完成', value: 'completed' },
  { text: '已取消', value: 'cancelled' }
])

// 统计信息
const stats = reactive({
  totalCount: 0,
  totalFee: 0,
  avgDuration: '0小时'
})

// 停车记录数据
const parkingRecords = ref([
  {
    id: 1,
    plateNumber: '京A12345',
    status: 'completed',
    statusText: '已完成',
    statusType: 'success',
    entryTime: '2025-01-20 08:30',
    exitTime: '2025-01-20 18:30',
    duration: '10小时',
    location: 'A区-123号',
    fee: 15.00
  },
  {
    id: 2,
    plateNumber: '京A12345',
    status: 'parking',
    statusText: '停车中',
    statusType: 'warning',
    entryTime: '2025-01-21 09:00',
    exitTime: '',
    duration: '',
    location: 'B区-456号',
    fee: 0
  },
  {
    id: 3,
    plateNumber: '京B67890',
    status: 'completed',
    statusText: '已完成',
    statusType: 'success',
    entryTime: '2025-01-19 14:00',
    exitTime: '2025-01-19 22:00',
    duration: '8小时',
    location: 'C区-789号',
    fee: 12.00
  }
])

// 加载状态
const loading = ref(false)
const hasMore = ref(true)

// Picker显示状态
const showTimeRangePicker = ref(false)
const showVehiclePicker = ref(false)
const showStatusPicker = ref(false)

// 筛选后的记录
const filteredRecords = computed(() => {
  let records = [...parkingRecords.value]
  
  // 按时间范围筛选
  if (filterData.timeRange !== 'all') {
    const now = new Date()
    let startDate
    switch (filterData.timeRange) {
      case '7days':
        startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
        break
      case '30days':
        startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)
        break
      case '3months':
        startDate = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000)
        break
    }
    records = records.filter(record => new Date(record.entryTime) >= startDate)
  }
  
  // 按车辆筛选
  if (filterData.vehicleId !== 'all') {
    records = records.filter(record => record.plateNumber === getVehicleText(filterData.vehicleId))
  }
  
  // 按状态筛选
  if (filterData.status !== 'all') {
    records = records.filter(record => record.status === filterData.status)
  }
  
  return records
})

// 获取时间范围文本
const getTimeRangeText = (value) => {
  const option = timeRangeOptions.value.find(opt => opt.value === value)
  return option ? option.text : '选择时间'
}

// 获取车辆文本
const getVehicleText = (value) => {
  const option = vehicleOptions.value.find(opt => opt.value === value)
  return option ? option.text : '选择车辆'
}

// 获取状态文本
const getStatusText = (value) => {
  const option = statusOptions.value.find(opt => opt.value === value)
  return option ? option.text : '选择状态'
}

// 时间范围变化
const onTimeRangeChange = (event) => {
  filterData.timeRange = event.value[0]
  showTimeRangePicker.value = false
  updateStats()
}

// 车辆变化
const onVehicleChange = (event) => {
  filterData.vehicleId = event.value[0]
  showVehiclePicker.value = false
  updateStats()
}

// 状态变化
const onStatusChange = (event) => {
  filterData.status = event.value[0]
  showStatusPicker.value = false
  updateStats()
}

// 更新统计信息
const updateStats = () => {
  const records = filteredRecords.value
  stats.totalCount = records.length
  stats.totalFee = records.reduce((sum, record) => sum + record.fee, 0).toFixed(2)
  
  const completedRecords = records.filter(record => record.status === 'completed')
  if (completedRecords.length > 0) {
    const totalHours = completedRecords.reduce((sum, record) => {
      const duration = record.duration
      const hours = parseInt(duration.replace('小时', ''))
      return sum + hours
    }, 0)
    stats.avgDuration = Math.round(totalHours / completedRecords.length) + '小时'
  }
}

// 查看详情
const viewDetail = (record) => {
  uni.navigateTo({
    url: `/pages/parking/record-detail?id=${record.id}`
  })
}

// 重新缴费
const rePay = (record) => {
  uni.navigateTo({
    url: `/pages/parking/payment?recordId=${record.id}&amount=${record.fee}`
  })
}

// 加载更多
const loadMore = async () => {
  if (loading.value) return
  
  try {
    loading.value = true
    
    // 模拟加载更多数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 这里可以调用API加载更多数据
    console.log('加载更多数据')
    
    // 模拟没有更多数据
    hasMore.value = false
    
  } catch (error) {
    console.error('加载更多失败', error)
  } finally {
    loading.value = false
  }
}

// 页面加载时初始化数据
onMounted(() => {
  console.log('停车记录页面加载完成')
  updateStats()
})
</script>

<style lang="scss" scoped>
.record-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 16px;
}

.filter-section,
.stats-section,
.record-list {
  margin-bottom: 16px;
  
  :deep(.u-card) {
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.filter-content {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 16px 0;
  
  .filter-item {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .filter-label {
      font-size: 14px;
      color: #333;
      white-space: nowrap;
    }
  }
}

.stats-content {
  display: flex;
  justify-content: space-around;
  padding: 20px 0;
  
  .stats-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .stats-number {
      font-size: 20px;
      font-weight: bold;
      color: #2d8cf0;
      margin-bottom: 4px;
    }
    
    .stats-label {
      font-size: 12px;
      color: #666;
    }
  }
}

.list-content {
  .record-item {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .record-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      
      .record-info {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .record-plate {
          font-size: 16px;
          color: #333;
          font-weight: 500;
        }
      }
      
      .record-fee {
        font-size: 16px;
        color: #ff4757;
        font-weight: 500;
      }
    }
    
    .record-details {
      margin-bottom: 12px;
      
      .detail-row {
        display: flex;
        margin-bottom: 4px;
        
        .detail-label {
          font-size: 12px;
          color: #666;
          width: 80px;
          flex-shrink: 0;
        }
        
        .detail-value {
          font-size: 12px;
          color: #333;
          flex: 1;
        }
      }
    }
    
    .record-actions {
      display: flex;
      gap: 8px;
    }
  }
}

.load-more {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  border-top: 1px solid #f0f0f0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
  
  .empty-text {
    font-size: 14px;
    color: #999;
    margin-top: 12px;
  }
}

// 响应式设计
@media (max-width: 480px) {
  .filter-content {
    flex-direction: column;
    gap: 8px;
    
    .filter-item {
      justify-content: space-between;
    }
  }
  
  .stats-content {
    padding: 16px 0;
    
    .stats-item {
      .stats-number {
        font-size: 18px;
      }
    }
  }
}
</style> 